package com.qianli.cashmama.trade.domain;

import java.util.HashSet;
import java.util.Set;

/**
 * 领域模型状态机签转
 * <p>
 * Created by scrack on 2017/7/21.
 */
public class StateMachine {
    /**
     * 合法签转路径列表
     */
    private Transition[] validTransitions;

    /**
     * 翻译后的所有签转集合
     */
    private final Set<String> translatedTransitions = new HashSet<String>();

    /**
     * 翻译后的所有接受操作集合
     */
    private final Set<String> translatedAcceptStatus = new HashSet<String>();

    /**
     * 分隔符
     */
    private final String DEMILITER = "|";

    // ~~~ 构造方法

    /**
     * 构造方法
     *
     * @param validTransitions 合法的迁转路径列表
     */
    public StateMachine(Transition[] validTransitions) {

        super();
        this.validTransitions = validTransitions;

        for (Transition transition : validTransitions) {

            //记录签转路径
            translatedTransitions.add(transition.getFromStatus() + DEMILITER
                    + transition.getAction() + DEMILITER
                    + transition.getToStatus());

            //记录接受的操作集合
            translatedAcceptStatus.add(transition.getFromStatus() + DEMILITER
                    + transition.getAction());
        }
    }


    /**
     * 验证签转路径是否存在。
     *
     * @param from   起始状态
     * @param action 业务动作
     * @param to     目标状态
     */
    public boolean checkTransition(int from, String action, int to) {

        //同状态严禁迁转
        String transition = from + DEMILITER + action + DEMILITER + to;

        return translatedTransitions.contains(transition);
    }

    /**
     * 验证操作在状态下是否合法。
     *
     * @param status 起始状态
     * @param action 业务动作
     * @return
     */
    public boolean checkAction(int status, String action) {

        String acceptAction = status + DEMILITER + action;

        return translatedAcceptStatus.contains(acceptAction);
    }

    public Transition[] getValidTransitions() {
        return validTransitions;
    }

    public StateMachine setValidTransitions(Transition[] validTransitions) {
        this.validTransitions = validTransitions;
        return this;
    }

    public Set<String> getTranslatedTransitions() {
        return translatedTransitions;
    }

    public Set<String> getTranslatedAcceptStatus() {
        return translatedAcceptStatus;
    }

    public String getDEMILITER() {
        return DEMILITER;
    }
}
